package com.wx.tnsadmin.controller;

import com.github.pagehelper.PageInfo;
import com.wx.common.api.CommonResult;
import com.wx.common.api.ResultCode;
import com.wx.tnsadmin.annotation.Log;
import com.wx.tnsadmin.model.UmsAdminModel;
import com.wx.tnsadmin.model.UmsAuthModel;
import com.wx.tnsadmin.model.UmsRoleModel;
import com.wx.tnsadmin.service.UmsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author:LLH
 * @Date:2020/8/10
 */

@Slf4j
@RequestMapping(value = "/admin")
@RestController
@Api(tags = "后台用户管理")
public class UmsAdminController {

    @Autowired
    private UmsAdminService umsAdminService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;


    @Log(operation = "后台登录")
    @ApiOperation(value = "后台登录", notes = "后台登录")
    @RequestMapping(value = "/loginAdmin", method = RequestMethod.POST)
    public CommonResult loginAdmin ( @RequestBody(required = false) UmsAdminModel umsAdmin) {
        try {
            List<UmsAuthModel> authList = umsAdminService.getAuthList ( umsAdmin.getUsername ( ) );
            List<UmsRoleModel> userRoleByUserName = umsAdminService.getUserRoleByUserName ( umsAdmin.getUsername ( ) );
            UmsAdminModel byUsername = umsAdminService.findByUsername ( umsAdmin.getUsername ( ) );
            String token = umsAdminService.loginAdmin ( umsAdmin.getUsername ( ),umsAdmin.getPassword ( ) );
            if (umsAdmin.getUsername ( ).equals ( "" ) || umsAdmin.getUsername ( ) == null || umsAdmin.getUsername ( ).isEmpty ( )) {
                return CommonResult.failed ( ResultCode.VALIDATE_FAILED,"用户名为空,登录失败!" );
            } else if (umsAdmin.getPassword ( ).equals ( "" ) || umsAdmin.getPassword ( ) == null || umsAdmin.getPassword ( ).isEmpty ( )) {
                return CommonResult.failed ( ResultCode.VALIDATE_FAILED,"密码为空,登录失败!" );
            } else if (byUsername.getAdmin_status ( ) != 1) {
                return CommonResult.failed ( ResultCode.VALIDATE_FAILED,"用户已被锁定，请联系管理员!" );
            } else if (token == null) {
                return CommonResult.failed ( ResultCode.VALIDATE_FAILED,"用户名或密码错误" );
            }
            Map<String, Object> tokenMap = new HashMap<> ( );
            tokenMap.put ( "tokenHead",tokenHead );
            tokenMap.put ( "token",token );
            tokenMap.put ( "username",umsAdmin.getUsername ( ) );
            tokenMap.put ( "role",userRoleByUserName );
            tokenMap.put ( "auth",authList );


            return CommonResult.success ( tokenMap,"登录成功!" );

        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @PreAuthorize("hasAuthority('tns:admin:findAllAdmin')")
    @Log(operation = "后台用户查询")
    @ApiOperation(value = "后台用户查询", notes = "后台用户查询")
    @RequestMapping(value = "/findAllAdmin", method = RequestMethod.GET)
    public CommonResult findAllAdmin () {
        List<UmsAdminModel> allAdmin = umsAdminService.findAllAdmin ( );
        try {
            if (CollectionUtils.isEmpty ( allAdmin )) {
                return CommonResult.failed ( "用户查询失败!" );
            } else {
                return CommonResult.success ( allAdmin,"用户查询成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @Log(operation = "后台用户ID查询")
    @ApiOperation(value = "后台用户ID查询", notes = "后台用户ID查询")
    @RequestMapping(value = "/findByAdminId", method = RequestMethod.GET)
    public CommonResult findByAdminId ( @RequestParam(required = false) String id ) {
        UmsAdminModel byAdminId = umsAdminService.findByAdminId ( id );
        try {
            if (id == null || id.equals ( 0 )) {
                return CommonResult.failed ( "用户ID查询失败!" );
            } else {
                return CommonResult.success ( byAdminId,"用户ID查询成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @PreAuthorize("hasAuthority('tns:admin:saveAdmin')")
    @Log(operation = "后台用户新增")
    @ApiOperation(value = "后台用户新增", notes = "后台用户新增")
    @RequestMapping(value = "/saveAdmin", method = RequestMethod.POST)
    public CommonResult saveAdmin ( @RequestBody(required = false) UmsAdminModel umsAdminModel ) {
        Integer integer = umsAdminService.saveAdmin ( umsAdminModel );
        try {
            if (integer < 0) {
                return CommonResult.failed ( "新增" + integer + "条数据失败!" );
            } else {
                return CommonResult.success ( umsAdminModel,"新增" + integer + "条数据成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @PreAuthorize("hasAuthority('tns:admin:updateAdmin')")
    @Log(operation = "后台用户修改")
    @ApiOperation(value = "后台用户修改", notes = "后台用户修改")
    @RequestMapping(value = "/updateAdmin", method = RequestMethod.POST)
    public CommonResult updateAdmin ( @RequestBody(required = false) UmsAdminModel umsAdminModel ) {
        Integer integer = umsAdminService.updateAdmin ( umsAdminModel );
        try {
            if (integer < 0) {
                return CommonResult.failed ( "修改" + integer + "条数据失败!" );
            } else {
                return CommonResult.success ( umsAdminModel,"修改" + integer + "条数据成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @PreAuthorize("hasAuthority('tns:admin:deleteAdminById')")
    @Log(operation = "后台用户删除")
    @ApiOperation(value = "后台用户删除", notes = "后台用户删除")
    @RequestMapping(value = "/deleteAdminById", method = RequestMethod.DELETE)
    public CommonResult deleteAdminById ( @RequestParam(required = false) String id ) {
        Integer integer = umsAdminService.deleteAdminById ( id );
        try {
            if (integer < 0) {
                return CommonResult.failed ( "删除" + integer + "条数据失败!" );
            } else {
                return CommonResult.success ( id,"删除" + integer + "条数据成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }


    @Log(operation = "后台用户分页")
    @ApiOperation(value = "后台用户分页", notes = "后台用户分页")
    @RequestMapping(value = "/findByAdminPage", method = RequestMethod.GET)
    public CommonResult findByAdminPage ( UmsAdminModel umsAdminModel ) {
        PageInfo byAdminPage = umsAdminService.findByAdminPage ( umsAdminModel );
        try {
            if (byAdminPage == null) {
                return CommonResult.failed ( "分页查询数据失败!" );
            } else {
                return CommonResult.success ( byAdminPage,"分页查询数据成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @Log(operation = "后台用户逻辑删除")
    @ApiOperation(value = "后台用户逻辑删除", notes = "后台用户逻辑删除")
    @RequestMapping(value = "/deleteAdminUpdate", method = RequestMethod.POST)
    public CommonResult deleteAdminUpdate ( @RequestParam(required = false) String id ) {
        Integer integer = umsAdminService.deleteAdminUpdate ( id );
        try {
            if (integer < 0) {
                return CommonResult.failed ( "逻辑删除" + integer + "条数据失败!" );
            } else {
                return CommonResult.success ( id,"逻辑删除" + integer + "条数据成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }


    @PreAuthorize("hasAuthority('tns:admin:deleteAdminAllById')")
    @Log(operation = "后台用户批量删除")
    @ApiOperation(value = "后台用户批量删除", notes = "后台用户批量删除")
    @RequestMapping(value = "/deleteAdminAllById", method = RequestMethod.DELETE)
    public CommonResult deleteAdminAllById ( @RequestParam String id ) {
        try {
            List list = new ArrayList ( );
            String[] strings = id.split ( "," );
            for (String string : strings) {
                list.add ( string );
            }
            Integer integer = umsAdminService.deleteAdminAllById ( list );
            if (integer == null) {
                return CommonResult.failed ( "用户批量删除失败" );
            } else {
                System.out.println ( "用户批量删除" + integer + "条数据成功！" );
                return CommonResult.success ( integer,"用户批量删除成功！" );
            }

        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }

    @Log(operation = "后台用户修改密码")
    @ApiOperation(value = "后台用户修改密码", notes = "后台用户修改密码")
    @RequestMapping(value = "/updateByPassword", method = RequestMethod.POST)
    public CommonResult updateByPassword ( @RequestParam("username") String username,
                                           @RequestParam("password") String password,
                                           @RequestParam("newpassword") String newpassword ) {
        UmsAdminModel byUsername = umsAdminService.findByUsername ( username );
        try {
            if (byUsername == null) {
                return CommonResult.failed ( "该用户不存在!" );
            } else if (!password.equals ( byUsername.getPassword ( ) )) {
                return CommonResult.failed ( "原密码错误!" );
            } else {
                umsAdminService.updateByPassword ( username,newpassword );
                System.out.println ( "修改密码为:" + newpassword );
                return CommonResult.success ( newpassword,"修改密码成功!" );
            }
        } catch (Exception e) {
            e.printStackTrace ( );
            return CommonResult.failed ( ResultCode.FAILED );
        }
    }


}
